package com.hhx.dao.impl;
import com.hhx.utils.BaseDao;
import com.hhx.dao.GoodsDao;
import com.hhx.entity.Goods;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;

public class GoodsDaoImpl implements GoodsDao {
    private final JdbcTemplate template = new JdbcTemplate(BaseDao.getDataSource());

    @Override
    public List<Goods> getAll(String name, Integer current, Integer limit) {
       StringBuilder sb = new StringBuilder();
       List<Object> params = new ArrayList<>();
       sb.append("select * from goods where 1=1 ");
       if (name!= null &&!name.isEmpty()) {
           sb.append("and goods_name like ? ");
           params.add("%" + name + "%");
       }
       sb.append(" order by create_date asc");
       sb.append(" limit ?,?");
       params.add((current - 1)*limit);
       params.add(limit);
       return template.query(sb.toString(),new BeanPropertyRowMapper<>(Goods.class),params.toArray());
       }
    @Override
    public int count(String name) {
        StringBuilder sb = new StringBuilder();
        List<Object> params = new ArrayList<>();
        sb.append("select count(*) from goods where 1=1 ");
        if (name!= null &&!name.isEmpty()) {
            sb.append("and goods_name like ? ");
            params.add("%" + name + "%");
        }
        return template.queryForObject(sb.toString(),Integer.class,params.toArray());
    }

    @Override
    public int add(Goods g) {
        String sql = "insert into goods values (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, default)";
        return template.update(sql, g.getItemId(), g.getGoodsName(), g.getGoodsType(), g.getGoodsBrand(), g.getGoodsPrice(), g.getGoodsSum(), g.getGoodsDesc(), g.getGoodsDiscount(), g.getGoodsImg());
    }

    @Override
    public int delete(String id) {
        String sql = "delete from goods where id = ?";
        return template.update(sql, id);
    }

    @Override
    public Goods getById(String id) {
        String sql = "select * from goods where id = ?";
        return template.queryForObject(sql, new BeanPropertyRowMapper<>(Goods.class), id);
    }

    @Override
    public int update(Goods g) {
        String sql = "update goods set item_id = ?, goods_name = ?, goods_type = ?, goods_brand = ?, goods_price = ?, goods_sum = ?, goods_desc = ?, goods_discount = ?, goods_img = ? where id = ?";
        return template.update(sql, g.getItemId(), g.getGoodsName(), g.getGoodsType(), g.getGoodsBrand(), g.getGoodsPrice(), g.getGoodsSum(), g.getGoodsDesc(), g.getGoodsDiscount(), g.getGoodsImg(), g.getId());
    }

}

